import { MessageTypeEnum, MethodNameEnum } from ".";
export default class UdcComponent {
    constructor(msgSdkInstance, context) {
        if (context) {
            this.context = {
                subComponents: [],
                ...context
            };
        }
        this.msgSdkInstance = msgSdkInstance;
    }
    context = null;
    /** IframeToolkit例 */
    msgSdkInstance = null;
    /** 生成组件UUID */
    createComponentUUID = (componentType) => {
        const uuid = "xxxx".replace(/[xy]/g, (c) => {
            const r = (Math.random() * 16) | 0;
            const v = c === "x" ? r : (r & 0x3) | 0x8;
            return `${v.toString(16)}`;
        });
        return `${componentType}_${uuid}_from_message`;
    };
    /** 获取组件上下文 */
    getContext = () => this.context;
    /** 插入组件 */
    insertComponent(components, methodConfig) {
        try {
            components.forEach(component => {
                const componentContext = component.getContext();
                componentContext.props?.customEvents?.forEach((customEvent) => {
                    this.msgSdkInstance.registerComponentCustomEvents({
                        id: componentContext.id,
                        ...customEvent
                    });
                    delete customEvent.func;
                });
                this.context.subComponents?.push(component.getContext());
            });
            this.msgSdkInstance?.postMessage({
                type: MessageTypeEnum.callMethod,
                methodName: MethodNameEnum.insertComponent,
                methodConfig,
                data: this.context,
            });
        }
        catch (e) {
            console.error(e);
        }
    }
    /** 创建组件 */
    createComponent(component) {
        component.isContract = true; // 创建的组件，也属于契约组件
        component.isCreateByMessage = true; // 由消息创建的标识
        component.id = !component.id ? this.createComponentUUID(component.type) : component.id;
        return new UdcComponent(this.msgSdkInstance, component);
    }
}
